package handler

import (
	"gin/global"
	user "gin/internal/pb/user"
	"gin/internal/request"
	"gin/tools"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"net/http"
)

const SKey = "this is a goods days1"
const Expire = 864800

func Login(c *gin.Context) {

	var req request.LoginForm
	err := c.ShouldBind(&req)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"message": "参数获取失败"})
		return
	}
	login, err := global.UserClient.Login(c, &user.LoginRequest{
		Mobile:   req.Mobile,
		Password: req.Password,
	})
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"message": "登录失败"})
		return
	}
	claims := tools.CustomClaims{
		ID: uint(login.Id),
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: Expire,
		},
	}
	newJWT := tools.NewJWT(SKey)
	token, err := newJWT.CreateToken(claims)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"message": "token创建失败"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"message": "登录成功", "data": token})
}
